# coding=utf-8
from hashlib import md5

from sqlalchemy import Column
from sqlalchemy.types import Integer, String

from app_admin.extensions.globalobject import GlobalObject
from app_admin.extensions.mysql.mysql_base import Base
from ..extensions.mysql.session import sessionCM


class Admins(Base):
    __tablename__ = 'admin_user'
    """ROLES = {
        'monitor':              0b1,            # 查看系统当前状态
        'watch_away_pool':      0b10,           # 查看奖池, 修改游戏配置,
        'watch_record':         0b100,          # 查看流水
        'modify_gold':          0b1000,         # 操作玩家上下分,
        'set_power':            0b1000000       # 修改系统用户权限,注册用户,禁用用户
        }
    """
    ROLES = {
        'monitor': 0b1,  # 查看系统当前状态
        'watch_away_pool': 0b10,  # 查看奖池, 修改游戏配置,
        'watch_record': 0b100,  # 查看流水
        'modify_gold': 0b1000,  # 操作玩家上下分,
        'set_power': 0b1000000  # 修改系统用户权限,注册用户,禁用用户
    }

    user_id = Column(Integer, autoincrement=True, primary_key=True)
    email = Column(String(255))
    phone = Column(String(11), unique=True, index=True, nullable=False)
    password_hash = Column(String(255), nullable=False)
    role = Column(Integer, default=ROLES['monitor'])
    status = Column(Integer, default=1)

    @property
    def password(self):
        return 'READ ONLY'

    def to_dict(self):
        return {"user_id": self.user_id, "email": self.email, "phone": self.phone, "role": self.role,
                "status": self.status}

    def validate_password(self, password):
        satl = GlobalObject().settings.get("SALT")
        m = md5(satl)
        password_hash = m.update(password)
        return self.password == password_hash

    @classmethod
    def get_user_by_phone(cls, phone_num):
        with sessionCM() as session:
            admin = session.query(Admins).filter_by(phone=phone_num).first()
            return admin.to_dict if admin else {}

    @classmethod
    def create(cls, email, phone, password, user_id=None):
        with sessionCM() as session:
            admin = session.query(Admins).filter_by(phone=phone).first()
            if admin:
                return 0
            new_user = cls(email, phone, password)
            session.add(new_user)
            session.commit()
            return new_user.id

    def get_id(self):
        return self.user_id
